package com.henu.art.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.henu.art.entity.Teacher;
import com.henu.art.model.LoginModel;
import com.henu.art.model.UserDetailModel;
import com.henu.art.service.AuthService;
import com.henu.art.service.Imlp.CustomRedis;
import com.henu.art.service.UserService;
import com.henu.art.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@RestController
@Slf4j
@RequestMapping("/user")
@Tag(name = "用户管理", description = "用户相关的操作接口")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private AuthService authService;
    @Resource
    private CustomRedis customRedis;

    @PostMapping("addUser")
    @Operation(summary = "添加用户", description = "添加一个新的用户")
    @ApiResponse(responseCode = "200", description = "添加成功")
    @ApiResponse(responseCode = "500", description = "添加失败")
    public Result<?> addUser(@RequestBody Teacher user) {
        return userService.save(user) ? Result.ok("添加成功") : Result.error("添加失败");
    }

    @GetMapping("getUserById")
    @Operation(summary = "根据ID获取用户", description = "根据用户ID获取用户信息")
    @ApiResponse(responseCode = "200", description = "用户存在")
    @ApiResponse(responseCode = "404", description = "用户不存在")
    public Result<?> getUserById(@RequestParam("id") @Parameter(description = "用户ID") String id) {
        Teacher user = userService.getById(id);
        return user == null ? Result.error("用户不存在") : Result.ok(user);
    }

    @GetMapping("getUserinfo")
    @Operation(summary = "获取用户信息", description = "根据token获取当前用户信息")
    @ApiResponse(responseCode = "200", description = "用户信息获取成功")
    @ApiResponse(responseCode = "404", description = "用户不存在")
    public Result<?> getUserinfo(@RequestHeader("token") @Parameter(description = "用户token") String token) {
        String username = authService.getUsernameByToken(token);
        if (Objects.equals(username, customRedis.getAdminUsername())) {
            Teacher user = Teacher.builder().name("管理员").isAdmin(1).build();
            return Result.ok(user);
        }
        Teacher user = userService.getById(authService.getUsernameByToken(token));
        return user == null ? Result.error("用户不存在") : Result.ok(user);
    }

    @GetMapping("getAllUser")
    @Operation(summary = "获取所有用户", description = "分页获取所有用户信息")
    @ApiResponse(responseCode = "200", description = "用户列表获取成功")
    public Result<?> getAllUser(@RequestParam(value = "pageNum", defaultValue = "1") @Parameter(description = "页码") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "5") @Parameter(description = "每页大小") Integer pageSize,
                                @RequestParam(value = "deleteStatus", defaultValue = "0") @Parameter(description = "删除状态") Integer deleteStatus) {
        IPage<Teacher> page = userService.getAllUser(pageNum, pageSize,  deleteStatus);
        return Result.ok(page);
    }

    @DeleteMapping("deleteUserById")
    @Operation(summary = "根据ID删除用户", description = "根据用户ID删除用户")
    @ApiResponse(responseCode = "200", description = "删除成功")
    @ApiResponse(responseCode = "500", description = "删除失败")
    public Result<?> deleteUserById(@RequestParam("id") @Parameter(description = "用户ID") String id) {
        return userService.removeById(id) ? Result.ok("删除成功") : Result.error("删除失败");
    }
    @GetMapping("redoDeleteUserById")
    @Operation(summary = "根据ID恢复用户", description = "根据用户ID恢复用户")
    @ApiResponse(responseCode = "200", description = "恢复成功")
    @ApiResponse(responseCode = "500", description = "恢复失败")
    public Result<?> redoDeleteUserById(@RequestParam("id") @Parameter(description = "用户ID") String id) {
        return userService.redoDeleteUserById(id) ? Result.ok("恢复成功") : Result.error("恢复失败");
    }

    @PutMapping("updateUser")
    @Operation(summary = "更新用户信息", description = "更新用户信息")
    @ApiResponse(responseCode = "200", description = "更新成功")
    @ApiResponse(responseCode = "500", description = "更新失败")
    public Result<?> updateUser(@RequestBody Teacher user) {
        try {
            return userService.updateById(user) ? Result.ok("修改成功") : Result.error("修改失败");
        } catch (RuntimeException e) {
            return Result.error("出现错误" + e.getMessage());
        }
    }

    @GetMapping("searchUser")
    @Operation(summary = "模糊搜索用户", description = "根据关键字模糊搜索用户，优先匹配姓名，其次匹配ID")
    @ApiResponse(responseCode = "200", description = "搜索成功")
    @ApiResponse(responseCode = "500", description = "搜索失败")
    public Result<?> searchUser(@RequestParam(value = "keyword") @Parameter(description = "搜索关键字") String keyword,
                                @RequestParam(value = "pageNum", defaultValue = "1") @Parameter(description = "页码") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "10") @Parameter(description = "每页大小") Integer pageSize) {
        QueryWrapper<Teacher> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", keyword).or().like("id", keyword);
        IPage<Teacher> page = userService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.ok(page);
    }

    @PutMapping("changePassword")
    @Operation(summary = "修改密码", description = "修改用户密码")
    @ApiResponse(responseCode = "200", description = "修改成功")
    @ApiResponse(responseCode = "500", description = "修改失败")
    public Result<?> changePassword(@RequestBody LoginModel loginModel, @RequestHeader("token") @Parameter(description = "用户token") String token) {
        String username = authService.getUsernameByToken(token);
        String newPassword = loginModel.getPassword();
        if (newPassword == null || newPassword.isEmpty()) {
            return Result.error("出现错误,请稍后再试");
        }
        try {
            return userService.changePassword(username, newPassword) ? Result.ok("修改成功") : Result.error("修改失败");
        } catch (Exception e) {
            log.error("修改密码时发生异常", e);
            return Result.error("修改密码失败，请稍后重试");
        }
    }

    @GetMapping("resetPassword")
    @Operation(summary = "重置密码", description = "重置用户密码")
    @ApiResponse(responseCode = "200", description = "重置成功")
    @ApiResponse(responseCode = "500", description = "重置失败")
    public Result<?> resetPassword(@RequestParam("username") @Parameter(description = "用户名") String username) {
        try {
            return userService.changePassword(username, "123456ab") ? Result.ok("重置成功") : Result.error("重置失败");

        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("getAllUserDetailInfo")
    @Operation(summary = "获取所有用户详细信息", description = "一次性查询并返回所有用户的详细信息")
    @ApiResponse(responseCode = "200", description = "查询成功")
    public Result<?> getAllUserDetailInfo() {
        try {
            List<UserDetailModel> userDetailModels = userService.getAllUserDetailInfo();
            if (userDetailModels == null || userDetailModels.isEmpty()) {
                return Result.ok("查询成功，但无数据");
            }
            return Result.ok(userDetailModels);
        } catch (Exception e) {
            log.error("获取用户详细信息失败", e);
            return Result.error("获取用户详细信息失败，请稍后重试");
        }
    }
}
